<template>
  <div class="buycom">
    <x-header :left-options="{showBack: true,  backText:''}">提交订单</x-header>

    <div class="weui-cells top">
       <router-link to="/dist/Selectadd" class="weui-cell weui-cell_access">
            <div class="weui-cell__bd">
                <p>{{defaultAdd.text}}</p>
                <small>{{defaultAdd.recipient}} {{defaultAdd.gender | sexTrue}}同学 {{defaultAdd.phone}}</small>
            </div>
            <div class="weui-cell__ft"></div>
        </router-link>
        <a class="weui-cell weui-cell_access" href="javascript:;" @click="show=!show">
            <div class="weui-cell__bd">
                <p>送达时间</p>
                <small>默认配送价格</small>
            </div>
            <div class="weui-cell__ft"> <p class="time-now">{{defaultTime}}</p><small>{{fee*0.01}}元</small></div>
        </a>
    </div>

    <div class="weui-cells">
      <a class="weui-cell weui-cell_access" href="javascript:;" @click="showHideOnBlur=!showHideOnBlur">
        <div class="weui-cell__bd">
            <p>优你红包</p>
        </div>
        <div class="weui-cell__ft">￥{{favorable*0.01}}</div>
      </a>
      <a class="weui-cell weui-cell_access" href="javascript:;">
        <div class="weui-cell__bd">
                <p>商家代金券</p>
        </div>
        <div class="weui-cell__ft">暂无可用代金券</div>
      </a>
    </div>
    
    <br>
    <div class="detail-list">
        <div class="detail-head">
          <div class="head-l">{{defaultTitle}}<!-- <div class="head-time">{{times[0]}}</div> --></div>
          <!-- <div class="head-r">&nbsp;<br><div></div></div> -->
        </div>

        <div class="detail-main">
          <ul>
            <li v-for="item in foods">
              <div class="detail-name">{{item.name}}</div>
              <div class="detail-num">X{{item.count}}</div>
              <div class="detail-price">￥{{item.price*item.count*0.01 | datadel}}</div>
            </li>
          </ul>
        </div>
    </div>

    <div class="detail-foot">
        <div class="foot-com">
          <div class="com-l">配送费</div>
          <div class="com-r">￥{{fee*0.01}}</div>
        </div>

        <div class="foot-com packet">
          <div class="com-l"><span class="iconfont icon-Dd_hb"></span>红包</div>
          <div class="com-r">-￥{{favorable*0.01}}</div>
        </div>

        <div class="foot-com com-total">
          <div class="com-l">总计:￥{{total*0.01 | datadel}} &nbsp;优惠￥{{favorable*0.01}} &nbsp;打赏￥{{reward*0.01}}</div>
          <div class="com-r">实付 <span>￥{{outPocket*0.01 | datadel}}</span></div>
        </div>
    </div>


    <div class="weui-cells">
        <a class="weui-cell weui-cell_access" href="javascript:;" @click="rangeShow = rangeShow">
            <div class="weui-cell__bd">
                <p>打赏</p>
            </div>
            <div class="weui-cell__ft">加急打赏,立马接单</div>
        </a>
        
        <div class="rang-cost" v-if="rangeShow">
            <div class="range-num">
              <p>不打赏</p>
              <p>2元</p>
              <p>5元</p>
              <p>10元</p>
            </div>
            <range v-model="data7" :min="1" :max="10" :step="3" :range-bar-height="6"></range>
        </div>

        <router-link  to="/dist/Mark" class="weui-cell weui-cell_access">
            <div class="weui-cell__bd">
                <p>备注</p>
            </div>
            <div class="weui-cell__ft">{{markDefault}}</div>
        </router-link>
    </div>

    <div class="buycom-foot">
      <div class="foot-l">待支付<span>￥{{outPocket*0.01 | datadel}}</span></div>
      <div class="foot-r" @click="pay()">提交订单</div>
    </div>


    <!--弹出框：时间-->
    <x-dialog v-model="show" class="dialog-demo time" :scroll="false">
        <p class="dialog-title">配送时间选择</p>
        <div class="img-box">
            <ul v-for="(time,index) in times">
              <li @click="selectedTime(time,index)" :class="{'isGray':index != 0}"><span v-if="index != 0">{{time}}</span><span v-if="index == 0">立即送出大约（{{time}}）送达</span><span class="cross iconfont icon-Sy_xialagou" v-if="index == current"></span></li>
            </ul>
        </div>
        <p class="dialog-footer"><span class="iconfont icon-Sy_cha" @click="show=false"></span></p>
    </x-dialog>
    <!--END dialog2-->

    <!--弹出框红包-->
    <x-dialog v-model="showHideOnBlur" class="dialog-demo hb" :scroll="true">
        <p class="dialog-title">优你红包</p>

        <div class="img-box-hb">
            <ul style="display:none">
              <li v-for="item in packet" @click="check(item)">
                <div class="hb-wrap">
                <div class="select-hb">
                  <div class="hb-l">
                    <p>{{item.title}}</p>
                    <p>有效期至{{item.time}}</p>
                  </div>
                  <div class="hb-r">
                    <p>￥<span>{{item.num}}</span></p>
                    <p>满{{item.term}}元可用</p>
                  </div>
                </div>
                <div class="hb-foot">{{item.footinfo}}</div>
                </div>
                <div :class="{check:item.checkone}"></div>
              </li>
            </ul>
        </div>

        <p class="dialog-footer dont-use-wrap"><span class="dont-use" @click="showHideOnBlur=false">不使用红包</span></p>
    </x-dialog>
    <!--END dialog3-->

  </div>

</template>

<script>
import Vue from 'vue'
import { XHeader, Group, XDialog, Scroller, Range } from 'vux'

export default {
  components: {
    XHeader,
    Group,
    XDialog,
    Scroller,
    Range
  },
  data:function(){
    return {
      isGray:false,
      isList:false,
      isDialog:false,
      isDialog1:false,
      show: false,
      isload:false,
      showNoScroll: false,
      showHideOnBlur: false,
      rangeShow:false,
      defaultTitle:null,
      current:0,
      top:'',
      info:'',
      addid:'',
      items:[],
      times:[],
      data7:null,
      markDefault:'口味、偏好等要求',
      timeStamp:[],
      postStamp:null,
      defaultTime:null,//默认时间
      defaultAdd:null,//默认地址
      foods:null,//添加到购物车的商品列表
      total:null,//商品未打折时总价
      feePost:null,//传到后台的fee(分)
      fee:null,//默认配送费
      reward:0,//打赏
      outPocket:null,//实际支付
      favorable:0,//优惠
      packet:[{title:'三食堂专享红包',time:'2017-12-12',num:6,term:30,footinfo:'仅限江汉大学文雅苑使用。仅限156235562使用',checkone:false},
        {title:'三食堂专享红包',time:'2017-12-12',num:7,term:30,footinfo:'仅限江汉大学文雅苑使用。仅限156235562使用',checkone:false},
        {title:'三食堂专享红包',time:'2017-12-12',num:8,term:30,footinfo:'仅限江汉大学文雅苑使用。仅限156235562使用',checkone:false},
      ]
    }
  },
  created() {
    this.$http.get('/api/address/me').then(function(res){
      var schoolId = res.data.address.school_id;
      this.$http.get('/api/schools/'+schoolId+'/extra-charges').then((res) => {
          var data = res.body.data;
          this.fee = data.fee+data.cut+data.pack;
          this.feePost = data.fee+data.cut+data.pack;
          this.total = this.$store.state.comtotal+this.fee;
          this.outPocket = this.$store.state.comtotal+this.fee-this.reward-this.favorable;
      });
    });

    this.$http.get('/api/delivery-addresses/default').then((res) => {
      this.defaultAdd = res.body.data;
      this.addid = res.body.data.id;
    })
  },
  mounted() {
    [30,45,60,75,90].forEach((i) => {
      this.times.push(this.create(i))
    })
    this.defaultTime = '立即送出(大约'+this.times[0]+'送达)'
    this.postStamp = this.timeStamp[0]
    this.foods = this.$store.state.selectedFoods;
    this.defaultTitle = this.$store.state.defaultCampousName + this.$store.state.currentName;
    if(this.$store.state.mark != null ){
      let mark = this.$store.state.mark
      if(mark.length>8){
        this.markDefault = mark.substring(0,8)+'...'
      }else{
        
        this.markDefault = mark;
      }
    }
  },
  methods:{
    watchData(val) {
      switch(val)
      {
      case 1:
        this.reward = 0;
        break;
      case 4:
        this.reward = 200;
        break;
      case 7:
        this.reward = 500;
        break;
      default:
        this.reward = 1000;
      }
    },
    getFoods() {
      var foods = [];
      this.foods.forEach((food)=>{
        foods.push({"id":food.id,"num":food.count});
      })
      return foods;
    },
    getObject() {
      var object = [];
      var objStr = null;
      this.foods.forEach((food)=>{
        object.push(food.name);
        objStr = object.join('|');
      })
      return objStr;
    },
    getTotal() {
      var total = null;
      this.foods.forEach((food)=>{
        total += food.count*food.price;
      })
      return total;//传到后台的总价,不做转换操作
    },
    create(t) {
      var odate = new Date();
      var timestamp = (Date.parse(odate) / 1000+t*60);
      var newdate = new Date(timestamp*1000);
      var h = newdate.getHours();
      var f = newdate.getMinutes();
      f<10?f = '0'+newdate.getMinutes():null;
      var time = h+':'+f;
      this.timeStamp.push(timestamp);
      return time;
    },
    selectedTime(time,index){
      this.show = false
      this.current = index
      this.defaultTime = '预约时间(大约'+time+'送达)'
      this.postStamp = this.timeStamp[index];
    },
    check(item){
      item.checkone=!item.checkone
      item.checkone?this.favorable = item.num*100:null
      this.showHideOnBlur=false
      this.outPocket = this.$store.state.comtotal+this.fee-this.reward-this.favorable
    },
    buylist:function(){
      this.isList = !this.isList;
    },
    onBridgeReady(data){
       var _this = this;
       WeixinJSBridge.invoke(
          'getBrandWCPayRequest', data,
           function(res){     
              if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                _this.$store.commit('DEFAULT_CAMPOUS_ID',0);
                _this.$router.push({path:'/dist/Home'});
              }
           }
       ); 
    },
    wxPay(data) {
      if (typeof WeixinJSBridge == "undefined"){
         if( document.addEventListener ){
             document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady(), false);
         }else if (document.attachEvent){
             document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady()); 
             document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady());
         }
      }else{
         this.onBridgeReady(data);
      }
    },
    pay() {
      var total = this.getTotal()+this.feePost;
      var foodArr = JSON.stringify(this.getFoods());
      var objStr = this.getObject();
      var timeStamp = this.postStamp;
      var markInfo  = this.$store.state.mark;
      var addId = this.addid;
      this.$http.post('/api/wx/prepay',{
          total_amount:total, time:timeStamp, foods:foodArr, subject:objStr, mark:markInfo, delivery_address_id:addId
      }).then((res) => {
          var config = res.body;
          var data = {
             "appId":config.appId,//appId     
             "timeStamp":config.timeStamp,//时间戳     
             "nonceStr":config.nonceStr, //随机串     
             "package":config.package,//扩展字段     
             "signType":config.signType,//签名方式    
             "paySign":config.paySign//微信签名 
          };
          this.wxPay(data);
      }).catch(function(res){
          alert('统一下单失败');
      });
    }
  },
  computed(){
    this.total = this.$store.state.comtotal;
  },
  watch:{
    data7: function (val, oldVal) {
      this.watchData(val);
    },  
  }
}

</script>

<style lang='less' scoped>
@import '~vux/src/styles/close';

.vux-header{
  background-color: #Fe4e43;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  width: 100%;
}
.buycom{
  margin-top: 5.3rem;
  margin-bottom: 5.6rem;
}
.buycom .top{
  background: url('/dist/static/img/top.png')  repeat-x;
  background-size: 100% 3px;
  padding-top:3px;
}
.top a{
  background: #fff;
}
.buycom-foot{
  display: flex;
  display: -webkit-flex;
  height: 5rem;
  line-height: 5rem;
  position: fixed;
  bottom: 0;
  width: 100%;
}
.foot-l{
  flex: 2;
  color: #3f3f3f;
  font-size: 18px;
  text-align: right;
  padding-right: 1rem;
  background-color: #fff;
}
.foot-l span{
  color: #ff4d4d!important;
}
.foot-r{
  flex: 1;
  background-color: #ff4d4d;
  text-align: center;
  color: #fff;
  font-size: 18px;
}

.detail-list{
  background-color:#fff;
  padding:1.5rem 2rem 1rem 1.5rem;
}
.detail-head{
  color:#969696;
  display:flex;
  display:-webkit-flex;
  padding-bottom:8px;
  border-bottom:1px solid #bababa;
}
.head-l{
  flex:1;
  font-size:16px;
}
.head-r{
  flex:1;
  font-size:12px;
  text-align:right;
}
.head-time{
  font-size:12px;
}
.detail-main{
  padding:12px 0;
}
.detail-main ul{
  list-style: none;
}
.detail-main ul li{
  display:flex;
  display:-webkit-flex;
  line-height:30px;
}
.detail-main  li div{
  flex:1;
  font-size:16px;
}
.detail-name{
  color:#3f3f3f;
}
.detail-num{
  text-align:center;
  color:#969696!important;
}
.detail-price{
  text-align:right;
}
.detail-foot{
  background-color:#fff;
  padding:0rem 2rem 1rem 1.5rem;
}
.detail-foot .foot-com:nth-child(1){
  margin-bottom: 0.5rem;
}
.foot-com{
  display:flex;
  display:-webkit-flex;
  font-size:16px;
  line-height:30px;
}
.com-l{
  flex:2;
}
.com-r{
  flex:1;
} 
.com-r{
  text-align:right!important;
}
.com-total{
  color:#969696;
}
.com-total .com-r span{
  color:#fe4e4c;
}

/* 弹出消息框样式 */
.dialog-demo {
  .weui-dialog{
    border-radius: 8px;
    padding-bottom: 8px;
    overflow: scroll!important;
    width: 70%;
  }
  .dialog-title {
    line-height: 40px;
    color: #969696;
    font-size:20px;
  }
  .img-box,.img-box-hb {
    height: 260px;
    overflow: scroll;
    margin:0 1.5rem;
    border-top:1px solid #bababa;
    li{
      font-size: 12px;
      text-align: left;
      padding: 9px 16px;
      color: #969696;
      position: relative;
    }
    li:nth-child(1){
      color: #ff4d4d;
    }
  }
  .img-box-hb{
    margin:0;
    padding: 0 1.5rem;
    background-color: #f6f5f5;
  }
  .vux-close {
    margin-top: 8px;
    margin-bottom: 8px;
  }
}
.check{
  position: absolute;
  top: 0;
  right: 0;
  height: 20px;
  width: 20px;
  background:url('/dist/static/img/checkone.png') no-repeat;
  background-position: top right;
  background-size:100%;
}
.check span{
  font-size: 10px;
}
.dialog-footer{
  background-color:#ff4d4d;
  color:#fff;
}
.dialog-footer .iconfont {
  font-size:26px;
}
.dialog-footer .dont-use{
  font-size: 18px;
  margin: 1rem 0;
}
.dont-use-wrap{
  padding: 0.5rem 0;
}
.buycom .time-now{
  color: #ff4d4d;
  font-size: 14px;
}
.packet{
  border-top:1px solid #bababa;
}
.packet .com-l span{
  color: #ff4d4d;
  margin-right: 1rem;
}
.hb-foot{
  margin-top: 0.5rem;
  font-size: 7px;
  color: #969696;
}
.select-hb{
  display: flex;
  display: -webkit-flex;
  padding-bottom: 0.5rem;
  border-bottom: 1px solid #bababa;
}
.hb .weui-dialog{
  background-color: #f6f6f6!important;
}
.hb li{
  background-color: #fff;
  border-radius: 0.5rem;
  margin: 0.5rem 0; 
  list-style: none;
}
.hb-l{
  padding-top:1rem;
  flex: 1;
}
.hb-l p:nth-child(1){
  font-size: 15px;
}
.hb-r{
  flex: 1;
  text-align: right;
  margin-top: -1rem;
}
.hb-r p:nth-child(1) span{
  font-size: 30px;
  margin-bottom:-1rem;
}
.rang-cost{
  border-top: 1px solid #bababa;
  height: 6rem;
  padding:1rem 2rem 2rem 2rem;
}
.range-num{
  display: flex;
  -webkit-display:flex;
  margin-bottom:1.5rem;
}
.range-num p{
  color: #969696;
  text-align: center;
  flex: 1;
  -webkit-flex:1;
}
.vux-range-input-box{
  margin-left: 30px!important;
}
.range-bar{
  background: url('/dist/static/img/h.png') no-repeat!important;
  background-size: 100%;
}
.range-bar .range-max,.range-bar .range-min{
  display: none!important;
}
.isGray{
  color: #969696!important;
}
.cross{
  position: absolute;
  top: 0.7rem;
  right: 0.8rem;
  font-size: 10px;
  color:#ffd161;
}
</style>